package com.wzw.skin_code;

import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.lang.reflect.Field;

import dalvik.system.DexClassLoader;

/**
 * @author : wangzw
 * @date : 21-1-22下午2:31
 * @desc :
 */
public class SkinResource {
    private static final String TAG = SkinResource.class.getSimpleName();
    private static SkinResource instance;
    private Resources skinResources;
    private Resources appResources;
    private String skinPackageName;
    private DexClassLoader dexClassLoader;


    public static SkinResource getInstance() {
        if (instance == null) {
            synchronized (SkinResource.class) {
                if (instance == null) {
                    instance = new SkinResource();
                }
            }
        }
        return instance;
    }

    public void init(DexClassLoader dexClassLoader, Resources resources, Resources appResources, String packageName) {
        this.dexClassLoader = dexClassLoader;
        this.skinResources = resources;
        this.appResources = appResources;
        this.skinPackageName = packageName;
    }


    public String getResName(int resId) {
        //R.drawable.ic_launcher
        return appResources.getResourceEntryName(resId);//ic_launcher   /colorPrimaryDark

    }


    public void setDrawable(ImageView imageView, String drawableName) {
        try {
            Class<?> aClass = dexClassLoader.loadClass(skinPackageName + ".R$mipmap");
            Field field = aClass.getField(drawableName);
            //获取到图片的id
            int anInt = field.getInt(R.id.class);
            imageView.setImageDrawable(skinResources.getDrawable(anInt));

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public void setTextColor(TextView textView, String colorName) {
        try {
            Class<?> aClass = dexClassLoader.loadClass(skinPackageName + ".R$color");
            Field field = aClass.getField(colorName);
            Log.d(TAG, "setTextColor: "+field.getName());
            int anInt = field.getInt(R.id.class);
            textView.setTextColor(skinResources.getColor(anInt));

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
